/**
 * 此文件专供文件上传下载等操作使用， file页面相关参照同级目录filePage.js
 */
import { fileDownload, fileUpload } from '@/api/file'

const state = {
  // 文件对象
  fileObject: {},
  // 上传百分比
  uploadPercent: 0
}

const mutations = {
  // 创建文件对象
  create_fileObject (state, { fileType, fileID, other }) {
    state.fileObject[fileType + '-' + fileID + '-' + other] = {
      startBytes: 0,
      endBytes: 1,
      fileArray: []
    }
  },
  // 设置文件数组
  set_fileObject (state, { fileType, fileID, other, index, value }) {
    if (state.fileObject[fileType + '-' + fileID + '-' + other]) {
      state.fileObject[fileType + '-' + fileID + '-' + other].fileArray[index] = value
    }
  },
  // 设置下载文件起始字节
  set_fileStartBytes (state, { fileType, fileID, other, startBytes }) {
    if (state.fileObject[fileType + '-' + fileID + '-' + other]) {
      state.fileObject[fileType + '-' + fileID + '-' + other].startBytes = startBytes
    }
  },
  // 设置下载文件结束字节
  set_fileEndBytes (state, { fileType, fileID, other, endBytes }) {
    if (state.fileObject[fileType + '-' + fileID + '-' + other]) {
      state.fileObject[fileType + '-' + fileID + '-' + other].endBytes = endBytes
    }
  },
  // 重置文件数组
  reset_fileObject (state, { fileType, fileID, other }) {
    delete state.fileObject[fileType + '-' + fileID + '-' + other]
  },
  // 设置上传百分比
  set_uploadPercent (state, percent) {
    state.uploadPercent = percent
  }
}

const actions = {
  // 下载文件
  downloadFile ({ state, commit, dispatch }, { fileType, fileID, other }) {
    return new Promise((resolve, reject) => {
      if (!state.fileObject[fileType + '-' + fileID + '-' + other]) {
        commit('create_fileObject', { fileType, fileID, other })
      } else {
        commit('reset_fileObject', { fileType, fileID, other })
        commit('create_fileObject', { fileType, fileID, other })
      }
      fileDownload(fileType, fileID, other, state.fileObject[fileType + '-' + fileID + '-' + other].startBytes, state.fileObject[fileType + '-' + fileID + '-' + other].endBytes).then(async res => {
        const content = res.headers['content-range'].substring(res.headers['content-range'].lastIndexOf('/') + 1) - 1
        let length = Math.ceil(content / 100000)
        length = length > 10 ? 10 : length
        const temp = length === 10 ? Math.ceil(content / length) : 100000
        const arr = []
        for (let i = 0; i < length; i++) {
          arr.push(i)
        }
        commit('set_fileEndBytes', { fileType, fileID, other, endBytes: -1 })
        commit('set_fileStartBytes', { fileType, fileID, other, startBytes: -temp })
        arr.forEach(async item => {
          if (state.fileObject[fileType + '-' + fileID + '-' + other]) {
            commit('set_fileStartBytes', { fileType, fileID, other, startBytes: state.fileObject[fileType + '-' + fileID + '-' + other].startBytes + temp })
            if (content - state.fileObject[fileType + '-' + fileID + '-' + other].endBytes > temp) {
              commit('set_fileEndBytes', { fileType, fileID, other, endBytes: state.fileObject[fileType + '-' + fileID + '-' + other].endBytes + temp })
            } else {
              commit('set_fileEndBytes', { fileType, fileID, other, endBytes: '' })
            }
            const result = await fileDownload(fileType, fileID, other, state.fileObject[fileType + '-' + fileID + '-' + other].startBytes, state.fileObject[fileType + '-' + fileID + '-' + other].endBytes)
            commit('set_fileObject', { fileType, fileID, other, index: item, value: result.data })
            let i
            for (i = 0; i < length; i++) {
              if (state.fileObject[fileType + '-' + fileID + '-' + other] && !state.fileObject[fileType + '-' + fileID + '-' + other].fileArray[i]) {
                break
              }
            }
            if (i === length) {
              if (state.fileObject[fileType + '-' + fileID + '-' + other]) {
                const blob = new Blob(state.fileObject[fileType + '-' + fileID + '-' + other].fileArray)
                commit('reset_fileObject', { fileType, fileID, other })
                resolve(blob)
              }
            }
          }
        })
      })
    })
  },
  // 上传文件
  uploadFile ({ commit }, { file }) {
    return new Promise((resolve, reject) => {
      fileUpload(file).then(res => {
        if (res && res.data && res.data.code !== 200) {
          commit('filePage/set_dialogData', {
            mainTips: [
              '上传失败'
            ],
            subTips: '不支持该文件类型',
            btnList: [
              {
                name: '返回上一层',
                color: 'white',
                type: 'back'
              }
            ],
            imgSrc: require('@/assets/status/error.png'),
            ifShowPercents: false
          }, { root: true })
        } else if (res && res.data) {
          resolve(res)
        } else {

        }
      }).catch(err => {
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
